package com.example.myapplication.api;

import android.util.Log;

import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class Api {
    private static String requestUrl;
    private static OkHttpClient client;
    private static HashMap<String,Object> mParams;
    public static Api api =  new Api();
    public Api(){

    }

    public static Api config(String url , HashMap<String,Object> params){

         client = new OkHttpClient.Builder().build();
        requestUrl = AppConfig.BASE_URL+url;
        mParams = params;

        return api;
    }

    public  void  postRequest(final TitleCallBack callBack){
        JSONObject jsonObject = new JSONObject(mParams);
        String jsonStR = jsonObject.toString();
        RequestBody requestBodyJson = RequestBody
                .create(MediaType
                        .parse("appLication/json;charset=UTF-8"), jsonStR);

        //创建Requst
        final Request request = new Request.Builder()
                .url(requestUrl)
                .addHeader("contentType", "appLication/json;charset=UTF-8")
                .post(requestBodyJson)
                .build();

        //创建call回调对象
        final Call call = client.newCall(request);

        //发起请求
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("onFailure", e.getMessage());
                callBack.onFailure(e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String result = request.body().toString();
                callBack.onSuccess(result);


            }
        });


    }
}
